//
//  GoodsDetailViewController.m
//  much
//
//  Created by weijunjie on 2019/1/8.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "GoodsDetailViewController.h"

#import "NewStoreDetialBigImageShowView.h"
#import "DetailView.h"
#import "UIImage+extend.h"
#import "GoodsModel.h"
#import "NewStoreImageScrollView.h"
#import "DeviceDataInfo.h"
#import "CLPlayerView.h"
#import "GoodsDetailTitleTableViewCell.h"
#import "GoodsDetailIntroduceTableViewCell.h"
#import "GoodsDetailSpecificationsTableViewCell.h"
#import "StoreStandardView.h"
#import "GoodsStandardModel.h"


#define SectionTag @"sectionTag"

typedef NS_ENUM(NSUInteger, DetailCellType) {
    StoreDetailTitleTableViewCellType = 1, // 标题Cell
    StoreDetailIntroduceTableViewCellType = 2, // 介绍Cell
    StoreDetailSpecificationsTableViewCellType = 3, // 规格Cell
    StoreDetailActivityTableViewCellType, // 活动Cell
    StoreDetailGetCouponTableViewCellType, // 领券Cell
    StoreDetailMerchandiseTableViewCellType, // 商品评价
    StoreDetailMerchantsTableViewCellType, // 商家Cell
    StoreDetailRecommendTableViewCellType, // 大家都在看与24小时推荐
    StoreDetailNormalTablViewCellType // 正常Cell
};
@interface GoodsDetailViewController () <DetailViewSectionDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) DetailView *detailView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *storeMessageHeadScrollBackGroundView; // 滚动视图的底视图
/** 滚动视图 */
@property (nonatomic, weak) NewStoreImageScrollView *imageScrollView;
@property (nonatomic, strong) CLPlayerView *playerView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, assign) CGFloat detailTitleTableHeight;

@end
@implementation GoodsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor lightGrayColor];
    [self.detailView reloadData];
    self.navigationView.hidden = YES;
}

- (NSMutableArray *)sectionArray {
    if (!_sectionArray) {
        _sectionArray = [[NSMutableArray alloc] initWithObjects:@{SectionTag:@(StoreDetailTitleTableViewCellType)}, @{SectionTag:@(StoreDetailIntroduceTableViewCellType)}, @{SectionTag:@(StoreDetailSpecificationsTableViewCellType)}, nil];
    }
    return _sectionArray;
}

- (void)setModel:(GoodsModel *)model {
    _model = model;
    // 标题cell高度
    self.detailTitleTableHeight = [GoodsDetailTitleTableViewCell calculateHeightWithModel:model];
    // 头部多图
    self.tableView.tableHeaderView = self.storeMessageHeadScrollBackGroundView;
    [self.tableView reloadData];
    
    // 请求判断是否为单规格
    [self requesetStandardInfo];
    
    // 加载底部商品详情
    NSString *urlStr = [NSString stringWithFormat:@"http://m.aurora.yuntujk.net:30003/goods-detail.html?sid=%@",model.sid];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_playerView destroyPlayer];
    _playerView = nil;
}

- (CLPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [[CLPlayerView alloc] init];
        _playerView.topToolBarHiddenType = TopToolBarHiddenAlways;
        _playerView.fullStatusBarHiddenType = FullStatusBarHiddenFollowToolBar;
        _playerView.progressPlayFinishColor = Color0108183;
        _playerView.videoFillMode = VideoFillModeResizeAspect;
        __weakConfigure
        [_playerView endPlay:^{
            //销毁播放器
            [__weakSelf.playerView destroyPlayer];
            __weakSelf.playerView = nil;
            //            __weakSelf.storeRemarkView.hidden = NO;
            //            __weakSelf.imageScrollView.storeRemarkView = nil;
        }];
    }
    return _playerView;
}


- (DetailView *) detailView {
    if (!_detailView) {
        _detailView = [[DetailView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavigationHeight_N() - 49)];
        _detailView.delegate = self;
        [self.view addSubview:_detailView];
        [_detailView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self.view);
        }];
    }
    return _detailView;
}

- (UITableView *) tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:_detailView.bounds];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    }
    return _webView;
}

/** 滚动视图 */
- (UIView *)storeMessageHeadScrollBackGroundView {
    if (!_storeMessageHeadScrollBackGroundView) {
        _storeMessageHeadScrollBackGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth )];
        _storeMessageHeadScrollBackGroundView.backgroundColor = [UIColor whiteColor];
        NSMutableArray * arr = [[NSMutableArray alloc] init];
        
        [self.model.spuImages enumerateObjectsUsingBlock:^(GoodsSpuImages * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString * str =  obj.imagePath;
            [arr addObject:str];
        }];
        
        if (arr.count > 0) {
            NewStoreImageScrollView *imageScrollView = [[NewStoreImageScrollView alloc] initWithFrame:_storeMessageHeadScrollBackGroundView.frame videoPath:self.model.videoPath];
            self.imageScrollView = imageScrollView;
            
            [_storeMessageHeadScrollBackGroundView addSubview:imageScrollView];
            __weakConfigure
            imageScrollView.clickItemOperationBlock = ^(UIView *v, UIView *pageView, NewStoreImageScrollView *imageScrollView) {
                NSInteger currentIndex = v.tag;
                if (currentIndex == 0 && v.subviews.count != 0) { // 点击的视频
                    if (!imageScrollView.agreePhoneNet && ![[DeviceDataInfo currentNetWork] isEqualToString:@"1"]) { // 非Wifi
                        [imageScrollView setCoverHidden:NO];
                    } else {
                        [imageScrollView setCoverHidden:YES];
                        [v addSubview:__weakSelf.playerView];
                        __weakSelf.playerView.pageView = pageView;
                        __weakSelf.playerView.frame = v.bounds;
                        __weakSelf.playerView.url = [NSURL URLWithString:imageScrollView.videoPath];
                        //                        __weakSelf.playerView.url = [NSURL URLWithString:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"];
                        //                        __weakSelf.playerView.url = [NSURL URLWithString:@"http://edge.ivideo.sina.com.cn/6376446.flv?KID=sina,viask&Expires=1532880000&ssig=oaqkshOYd5"];
                        
                        imageScrollView.maskView = __weakSelf.playerView.maskView;
                        [__weakSelf.playerView playVideo];
                    }
                } else {
                    [__weakSelf showBigImage:arr imagePath:arr[currentIndex]];
                }
            };
            
            imageScrollView.imageURLStringsGroup = arr;
        }
    }
    return _storeMessageHeadScrollBackGroundView;
}

- (void)showBigImage:(NSArray *)imagesArray imagePath:(NSString *)imagePath {
    NSString * imageUrl = imagePath;
    
    __block NSInteger index = 0;
    [imagesArray enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([imageUrl isEqualToString:obj]) {
            index = idx;
            * stop = YES;
        }
    }];
    NSMutableArray * arr = [[NSMutableArray alloc] initWithArray:imagesArray];
    
    NewStoreDetialBigImageShowView * detialBigImageShowView = [[NewStoreDetialBigImageShowView alloc] initWithFrame:self.view.bounds bigImgUrlsArray:arr bigImgIndex:index];
    [self.view addSubview:detialBigImageShowView];
}

#pragma mark DetailViewSectionDelegate
- (UIView *) viewAtTop {
    return self.tableView;
}

- (NSUInteger ) numberOfSections {
    return 1;
}

- (NSString *) titleOfSectionAt:(NSUInteger )index {
    return @"";
}

- (UIView *) viewOfSectionAt:(NSUInteger ) index {
    return self.webView;
}

- (void) didChangeToSection:(NSUInteger) index view:(UIView *) view {
//    NSString *url = urls[index];
//    UIWebView *webView = (UIWebView *) view;
//    if (!webView.request) {
//        [webView stopLoading];
//        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
//    }
}

- (void)bottomViewShowed:(BOOL)appear {
    if (self.canSlid) {
        self.canSlid(!appear);
    }
}

#pragma mark == tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionArray.count;
    return [self.sectionArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger type = [self.sectionArray[indexPath.row][SectionTag] integerValue];
    
    switch (type) {
        case StoreDetailTitleTableViewCellType: // 标题
            return [self goodsDetailTitleTableViewCellMethod:tableView];
            break;
        case StoreDetailIntroduceTableViewCellType: // 介绍
            return [self goodsDetailIntroduceTableViewCellMethod:tableView];
            break;
        case StoreDetailSpecificationsTableViewCellType: // 规格
            return [self goodsSpecificationsTableViewCellMethod:tableView];
            break;
        default:
            return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell"];
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger type = [self.sectionArray[indexPath.row][SectionTag] integerValue];
    switch (type) {
        case StoreDetailIntroduceTableViewCellType: // 介绍
            break;
        case StoreDetailSpecificationsTableViewCellType: // 规格
            [self showGoodsStandardView];
            break;
        default:
            break;
    }
}


/**
 获取规格数据,用于判断是否是单规格
 */
- (void)requesetStandardInfo {
    [MuchStoreRequestManager storeDetailStandardInfoWithSpuSid:self.model.sid successBlock:^(GoodsStandardModel *_Nonnull standardModel) {
        NSInteger skuCount = standardModel.spuSpecifics.count;
        if (skuCount == 1) { // 单规格,默认选中
            // 取出第一个规格的sid
            GoodsStandardModel *spuSpecific = standardModel.spuSpecifics.firstObject;
            GoodsStandardModel *children = spuSpecific.children.firstObject;
            NSString *sid = children.sid;
            
            // 通过规格sid去获取详细数据
            for (GoodsStandardModel *itemSku in standardModel.itemSkuList) {
                if ([itemSku.specificCode isEqualToString:sid]) {
                    self.model.sellingPrice = itemSku.sellingPrice;
                    self.model.memberPrice = itemSku.memberPrice;
                    self.model.employeePrice = itemSku.employeePrice;
                    self.model.sellingDiscount = itemSku.sellingDiscount;
                    self.model.memberDiscount = itemSku.memberDiscount;
                    self.model.employeeDiscount = itemSku.employeeDiscount;
                    self.model.selectedSkuSid = itemSku.skuSid;
                    self.model.selectedStandardName = itemSku.value;
                    self.model.inventoryCount = itemSku.inventoryCount;
                    self.model.minCount = itemSku.minCount;
                    [self.tableView reloadData];
                    break;
                }
            }
        }
    } failureBlock:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
    }];
}

- (void)showGoodsStandardView {
    [SVProgressHUD showWithStatus:@"加载中..."];
    // 获取规格
    [MuchStoreRequestManager storeDetailStandardInfoWithSpuSid:self.model.sid successBlock:^(id  _Nonnull responseObject) {
        [SVProgressHUD dismiss];
        StoreStandardView *gPStandardView = [[StoreStandardView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 300)];
        __weakConfigure
        gPStandardView.updateStoreDetailInfoBlock = ^{
            [__weakSelf.tableView reloadData];
        };
        gPStandardView.backgroundColor = [UIColor whiteColor];
        gPStandardView.goodsModel = self.model;
        TYAlertController * alertController = [TYAlertController alertControllerWithAlertView:gPStandardView preferredStyle:TYAlertControllerStyleActionSheet];
        alertController.backgoundTapDismissEnable = YES;
        
        gPStandardView.goodsModel = self.model;
        gPStandardView.standardModel = responseObject;
        gPStandardView.alertController = alertController;
        [self presentViewController:alertController animated:YES completion:nil];
    } failureBlock:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
    }];
}

/** 标题Cell */
- (GoodsDetailTitleTableViewCell *)goodsDetailTitleTableViewCellMethod:(UITableView *)tableView {
    GoodsDetailTitleTableViewCell *cell = [GoodsDetailTitleTableViewCell detailTitleTableViewCellWithTableView:tableView];
    cell.model = self.model;
    return cell;
}

/** 介绍Cell */
- (GoodsDetailIntroduceTableViewCell *)goodsDetailIntroduceTableViewCellMethod:(UITableView *)tableView {
    GoodsDetailIntroduceTableViewCell *cell = [GoodsDetailIntroduceTableViewCell detailIntroduceTableViewCellWithTableView:tableView];
    return cell;
}

/** 规格Cell */
- (GoodsDetailSpecificationsTableViewCell *)goodsSpecificationsTableViewCellMethod:(UITableView *)tableView {
    GoodsDetailSpecificationsTableViewCell *cell = [GoodsDetailSpecificationsTableViewCell detailSpecificationsTableViewCellWithTableView:tableView];
    cell.model = self.model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch ([self.sectionArray[indexPath.row][SectionTag] integerValue]) {
        case StoreDetailTitleTableViewCellType: // 标题
            return self.detailTitleTableHeight;
            break;
        case StoreDetailIntroduceTableViewCellType: // 介绍
            return 90;
            break;
        case StoreDetailSpecificationsTableViewCellType: // 规格
            return 54;
            break;
        default:
            return 0;
            break;
    }
}
@end
